import * as React from 'react';
import {Component} from 'react'; 
import {TextField,Checkbox,Label, IIconProps,CommandBarButton, Stack, IStackStyles, FontIcon, MessageBar,MessageBarType,} from '@fluentui/react';  
import http from './RequestUtl.ts';
import './JobEditor.css';

const addIcon: IIconProps = { iconName: 'Add' };
const stackStyles: Partial<IStackStyles> = { 
  root: {
    height: 30,
    marginTop:2,
  }
};

class CronItem{
  id:String;
  cron:String;
  visbale:Boolean;
  action:String;//'','add','edit','delete'
  constructor(_id:string,_cron:string,_visbale:Boolean,_action:String) { 
    this.id = _id; 
    this.cron = _cron; 
    this.visbale = _visbale; 
    this.action = _action; 
  }  
}
 
class JobEditor extends Component<any,any> { 
  constructor(props){
    super(props);  
    this.state={ 
      newJobDetail:props.newJobDetail,
      addCronValue:'',
      messageBarVisable:false,
      messageBarType:MessageBarType,
      messageBarMsgContent:'',
    }
  }

  render(){
    return (
      <>
       {
          this.state.messageBarVisable &&(
            <MessageBar delayedRender={false} messageBarType={this.state.messageBarType} 
          >
            {this.state.messageBarMsgContent}
          </MessageBar>
          )
        }
        <div className='jobeditform'>
          <div className='job_left'>
            <div><TextField label="任务Id:" name='jobId' defaultValue={this.state.newJobDetail.jobId} onChange={this._JobDetailChange.bind(this)}/></div>
            <div><TextField label="任务分组:" name='groupName' defaultValue={this.state.newJobDetail.groupName} onChange={this._JobDetailChange.bind(this)} /></div>
            <div><TextField label="任务描述:" name='description' defaultValue={this.state.newJobDetail.description} onChange={this._JobDetailChange.bind(this)}  multiline rows={3}/></div>
            <div><TextField label="程序集名称:" name='assemblyName' defaultValue={this.state.newJobDetail.assemblyName} onChange={this._JobDetailChange.bind(this)} /></div>
            <div><TextField label="任务类型:" name='jobType' defaultValue={this.state.newJobDetail.jobType} onChange={this._JobDetailChange.bind(this)} /></div>
            <div><Label>任务串行/并行:</Label></div>
            <div className='form_row'>
              <Checkbox label="串行" id="concurrent_1" checked={!(this.state.newJobDetail.concurrent)} onChange={this._onConcurrentChange.bind(this)}/>
              <Checkbox label="并行" id="concurrent_2" checked={this.state.newJobDetail.concurrent} onChange={this._onConcurrentChange.bind(this)}/>
            </div>
          </div>
          <div className='job_right'>
            <div className='triggerTitle'>
              <label>作业定时作业触发器</label>
            </div> 
            <div className='triggerBody'>
              <div className='triggerBar'>
                <div className='crontxt'><TextField label="Cron:" required underlined  onChange={this._onCronChange.bind(this)}/></div>
                <div className='addbtn'>
                  <Stack horizontal styles={stackStyles}>
                    <CommandBarButton iconProps={addIcon} text="添加" onClick={this._addTriggerCron.bind(this)}/>
                  </Stack>
                </div>
              </div> 
              <div className='triggerList'>
                  {
                    this.state.newJobDetail.cronList?this.state.newJobDetail.cronList.map((v, i) => {
                      if(v.visbale){
                        return <div className='cronItem' key={i}>
                          <div className='sortNo'>{(i+1)}</div>
                          <FontIcon iconName='DateTimeMirrored' className='cronicon'/>
                          <div className='cronTxt'>{v.cron}</div>
                          <div className='crondel' defaultValue={v.cron} onClick={this._DelTriggerCron.bind(this,v)}><FontIcon iconName='CalculatorMultiply' className='crondelicon'/></div>
                        </div>
                      }
                    }):undefined
                  }
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }

  componentDidMount(){ 
    const Me=this;
    console.log("=================组件已经挂载了"); 
    console.log(this.state.newJobDetail); 
  }

  /**
   * 串行/并行 切换事件
   * @param ev 
   * @param isChecked 
   */
  _onConcurrentChange(ev?: React.FormEvent<HTMLElement | HTMLInputElement>, isChecked?: boolean){
    let Me=this;
    let _newJobDetail=Me.state.newJobDetail;
    if(ev && ev.currentTarget && ev.currentTarget.id==="concurrent_1"){
      _newJobDetail.concurrent=!isChecked; 
    }else{
      _newJobDetail.concurrent=isChecked;
    }
    Me.setState({newJobDetail:_newJobDetail});
  }
  
  /**
   * Cron 表达式值修改
   * @param event 事件
   * @param newValue 修改
   */
  _onCronChange(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string){
    let Me=this;
    Me.setState({addCronValue:newValue});
  }
  
  /**
   * 新增触发器
   * @returns 
   */
  _addTriggerCron(){
    let Me=this; 
    let _newJobDetail=Me.state.newJobDetail;
    let _cronList=_newJobDetail.cronList;
    const _tempcron=new CronItem('',Me.state.addCronValue,true,'add');
    if(_cronList.length>=5){
      showMessageBar(Me,MessageBarType.error,'同一个作业,最多只能添加5个触发器');
      HideMessageBar(Me);
      return;
    }
    if(_tempcron.cron && _tempcron.cron!==''){}else{
      Me.setState({
        messageBarVisable:true,
        messageBarType:MessageBarType.error,
        messageBarMsgContent:'触发器cron表达式不能为空',
      });
      HideMessageBar(Me);
      return;
    }

    if(!CheckIsRep(_cronList,_tempcron)){
      _cronList.push(_tempcron);
      _newJobDetail.cronList=_cronList;
      Me.setState({newJobDetail:_newJobDetail});
    }else{
      Me.setState({
        messageBarVisable:true,
        messageBarType:MessageBarType.error,
        messageBarMsgContent:'相同触发器已存在，无法添加',
      });
      HideMessageBar(Me);
      return;
    }
  }

  /**
   * 删除触发器
   */
  _DelTriggerCron(_cron:CronItem){
    let Me=this; 
    let _newJobDetail=Me.state.newJobDetail;
    let _cronList=_newJobDetail.cronList; 
    let _delIndex=-1;
    if(_cronList && _cronList.length>0){
      for(let i=0;i<_cronList.length;i++) {
        if (_cronList[i].cron===_cron.cron) {
          _cronList[i].visbale=false;
          _cronList[i].action='delete';
          _delIndex=i;
          break;
        }
      }
    } 
    if(_delIndex>-1){
      _cronList.splice(_delIndex,1);
    }

    _newJobDetail.cronList=_cronList;
    Me.setState({newJobDetail:_newJobDetail});
  }

  /**
   * 作业属性详情变更
   */
   _JobDetailChange(event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string){
      let Me=this;
      let _newJobDetail=Me.state.newJobDetail;
      _newJobDetail[event.currentTarget.name]=newValue;
      Me.setState({newJobDetail:_newJobDetail});
  }

  /**
   * 获取作业详情数据
   */
  saveJobDetail(_callfun:Function){
    let Me=this;
    let _model=Me.state.newJobDetail;
    // assemblyName:"", 
    // concurrent:false,
    // description:"",
    // groupName:"",
    // includeAnnotations:false,
    // jobId:"",
    // jobType:"",
    // properties:"{}",
    // updatedTime:"",
    // cronList:[],
    let bolSaveSucced=true;
    if(bolSaveSucced && IsNull(_model.jobId)){
      showMessageBar(Me,MessageBarType.error,'任务Id不能为空');
      HideMessageBar(Me);
      bolSaveSucced=false;
    }
    if(bolSaveSucced && IsNull(_model.groupName)){
      showMessageBar(Me,MessageBarType.error,'分组名称不能为空');
      HideMessageBar(Me);
      bolSaveSucced=false;
    }
    if(bolSaveSucced && IsNull(_model.assemblyName)){
      showMessageBar(Me,MessageBarType.error,'应用程序集不能为空');
      HideMessageBar(Me);
      bolSaveSucced=false;
    }
    if(bolSaveSucced && IsNull(_model.jobType)){
      showMessageBar(Me,MessageBarType.error,'任务类型不能为空');
      HideMessageBar(Me);
      bolSaveSucced=false;
    }

    if(bolSaveSucced && _model.cronList.length<=0){
      showMessageBar(Me,MessageBarType.error,'需要添加作业定时触发器');
      HideMessageBar(Me);
      bolSaveSucced=false;
    } 
    if(bolSaveSucced){
      http.post("schedule/api/job-save",_model).then(function(result){
        if(result.data.code===200){
          showMessageBar(Me,MessageBarType.success,"作业保存成功!");
          HideMessageBar(Me,_callfun); 
        }else{
          showMessageBar(Me,MessageBarType.error,result.data.msg);
          HideMessageBar(Me);
        }
      });
    }
  }
};
function IsNull(value:Object){
  if(value==null) return true;
  if(typeof(value)==="string" && value===""){
    return true;
  }
  return false;
}

function CheckIsRep(_crolist:Array<CronItem>,_newcro:CronItem){
  let  bolIsRep:Boolean =false;
  if(_crolist && _crolist.length>0){
    for(const _item of _crolist) {
      if (_item.cron===_newcro.cron) {
        bolIsRep= true;
        break;
      }
    }
  }
  return bolIsRep;
}

function showMessageBar(control:JobEditor,msgbarType:MessageBarType,msgContent:String){
  control.setState({
    messageBarVisable:true,
    messageBarType:msgbarType,
    messageBarMsgContent:msgContent,
  });
}
function HideMessageBar(control:JobEditor,callfun?:Function){
  setTimeout(() => {
    control.setState({messageBarVisable:false})

    if(callfun) callfun();
  }, 1000);
}
 
export default JobEditor